package chess;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This class is a custom solution to read text files of a unique and predetermined format.
 * Simply, this class enables the reading of any amount of string information, with both a variable amount of items and data fields.
 * All read data is put into ArrayList<String>[]s, all of which are returned as a 2d array.
 * While reading data of this type in this format is universally applicable, it works especially well within our Chess framework.
 * @author Ben
 */
public class GroupsHelper
{
	@SuppressWarnings("unchecked")
	public static ArrayList<String>[][] importData(String file)
	{
		try
		{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			int numItems = Integer.parseInt(reader.readLine());
			int numFields = Integer.parseInt(reader.readLine());
			ArrayList<String>[][] groupInformation = new ArrayList[numFields][numItems];

			ArrayList<String>[] fieldData = new ArrayList[numFields];
			for(int y = 0; y < numFields; y++)
				fieldData[y] = new ArrayList<String>();

			int x = 0;
			int infoType = 0;
			while(x < numItems)
			{
				String line = reader.readLine();
				if(line == null)
					break;

				if(line.equals("!0"))
				{
					infoType = 0;
					for(int y = 0; y < numFields; y++)
						groupInformation[y][x] = fieldData[y];

					fieldData = new ArrayList[numFields];
					for(int y = 0; y < numFields; y++)
						fieldData[y] = new ArrayList<String>();
					x++;
				}
				else if(line.contains("!"))
					infoType = Integer.parseInt(line.substring(1,2));
				else if (!(line.equals("")))
					fieldData[infoType].add(line);		
			}
			return groupInformation;
		}
		catch(IOException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
